package com.dmpb.ping.core;

import javax.sound.sampled.*;
import java.io.IOException;
import java.net.URL;

/**
 * Created by yusb on 2017/12/5.
 */
public class Sound
{

    public void alarm(){
        AudioFormat format;
        AudioInputStream audio;
        SourceDataLine auline = null;
        DataLine.Info info;
        try {
            System.out.println("Start");
            audio = getResource();
            format = audio.getFormat();
            info = new DataLine.Info(SourceDataLine.class, format);
            auline = (SourceDataLine) AudioSystem.getLine(info);
            auline.open(format);
            auline.start();
            int nBytesRead = 0;
            byte[] abData = new byte[524288];
            while (nBytesRead != -1) {
                nBytesRead = audio.read(abData, 0, abData.length);
                if (nBytesRead >= 0) {
                    auline.write(abData, 0, nBytesRead);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }  finally {
            auline.drain();
            auline.close();
        }
    }

    private AudioInputStream getResource(){
        URL url = this.getClass().getClassLoader().getResource("alarm.wav");
        try {
            return AudioSystem.getAudioInputStream(url);
        } catch (UnsupportedAudioFileException | IOException e) {
            e.printStackTrace();
            throw new RuntimeException("程序出现非法错误");
        }
    }

    public static void main(String[] args) {
        Sound sound = new Sound();
        sound.alarm();
    }
}